/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Discribe：模拟角色行走时头部的晃动
* CreateTime：2020-05-11 10:26:50
* Version：1.0
* Modify Recoder：
*************************************************/

using System;
using UnityEngine;

namespace TinyToolKit
{
    [Serializable]
    public class CurveControlledBob
    {
        //水平或垂直方向的摇动范围
        public float horizontalBobRange = 0.1f;
        public float verticalBobRange = 0.1f;
        public float verticalToHorizontalRatio = 2;

        public AnimationCurve bobCurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(0.5f, 1f),
            new Keyframe(1f, 0f), new Keyframe(1.5f, -1f), new Keyframe(2f, 0f));
        
        private float _cyclePosX;
        private float _cyclePosY;
        private float _bobBaseInterval;//摇动的步伐间隔
        private Vector3 _originalCameraPos;
        private float _time;

        public void Setup(Camera camera, float bobBaseInterval)
        {
            _bobBaseInterval = bobBaseInterval;
            _originalCameraPos = camera.transform.localPosition;
            // 获取摇动曲线的周期时间，即最后一个Keyframe的时间
            _time = bobCurve[bobCurve.length - 1].time;
        }

        //实现头部摇动
        public Vector3 DoHeadBob(float speed)
        {
            float xPos = _originalCameraPos.x + (bobCurve.Evaluate(_cyclePosX) * horizontalBobRange);
            float yPos = _originalCameraPos.y + (bobCurve.Evaluate(_cyclePosY) * verticalBobRange);

            float dis = (speed * Time.deltaTime) / _bobBaseInterval;
            _cyclePosX += dis;
            _cyclePosY += dis * verticalToHorizontalRatio;
            if (_cyclePosX > _time)  
                _cyclePosX = _cyclePosX - _time;
            
            if (_cyclePosY > _time)
                _cyclePosY = _cyclePosY - _time;
            
            return new Vector3(xPos,yPos,0f);
        }
    }
}
